/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.headerfooter.songhang.smartheaderfooterrecyclerview;

import com.headerfooter.songhang.library.GridViewAdapter;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.utils.PacMap;

import java.util.ArrayList;
import java.util.List;

/**
 * 网格布局界面
 */
public class GridAbility extends Ability implements Component.ClickedListener{
    private Text title;
    private Image menu;
    private ListContainer recyclerView;
    private DirectionalLayout headerView;
    private DirectionalLayout footerView;
    private MenuDialog menuDialog;
    private DirectionalLayout toastLayout;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        title = (Text) findComponentById(ResourceTable.Id_title);
        menu = (Image) findComponentById(ResourceTable.Id_menu);

        recyclerView = (ListContainer) findComponentById(ResourceTable.Id_recyclerview);

        menu.setClickedListener(component1 -> {
            int screenWidth = AttrHelper.vp2px(250, getContext());
            int menuHeight = AttrHelper.vp2px(150, getContext());
            menuDialog = new MenuDialog(getContext(), menu, screenWidth, menuHeight, ResourceTable.Layout_menu_tab);
            menuDialog.initListener(GridAbility.this);
            menuDialog.show();
        });
        initHeadAndFooterView();

        showGrid();
        title.setText("GridLayoutManager");
    }

    private void initHeadAndFooterView() {
        // header view
        ComponentContainer.LayoutConfig layoutParams = new ComponentContainer.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT, 400);
        layoutParams.setMargins(10, 10, 10, 10);

        headerView = new DirectionalLayout(getContext());
        headerView.setLayoutConfig(layoutParams);
        ShapeElement background = new ShapeElement();
        background.setRgbColor(new RgbColor(0, 0, 255));
        headerView.setBackground(background);
        Text head = new Text(getContext());
        head.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_PARENT));
        head.setTextColor(Color.WHITE);
        head.setTextAlignment(TextAlignment.CENTER);
        head.setText("THIS IS HEADER VIEW");
        head.setTextSize(14, Text.TextSizeType.VP);
        headerView.addComponent(head);

        // footer view
        footerView = new DirectionalLayout(getContext());
        footerView.setLayoutConfig(layoutParams);
        background = new ShapeElement();
        background.setRgbColor(new RgbColor(255, 0, 0));
        footerView.setBackground(background);
        Text footer = new Text(getContext());
        footer.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_PARENT));
        footer.setText("THIS IS FOOTER VIEW");
        footer.setTextAlignment(TextAlignment.CENTER);
        footer.setTextColor(Color.WHITE);
        footer.setTextSize(14, Text.TextSizeType.VP);
        footerView.addComponent(footer);
    }

    private void showGrid() {
        toastLayout = (DirectionalLayout) LayoutScatter.getInstance(this).parse(
                ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) toastLayout.findComponentById(ResourceTable.Id_msg_toast);
        text.setText("GridLayoutManager");
        new ToastDialog(getContext())
                .setContentCustomComponent(toastLayout)
                .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                .setAlignment(LayoutAlignment.BOTTOM)
                .setOffset(0, 100)
                .setTransparent(true)
                .show();

        ArrayList<String> mList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            mList.add("position:" + i);
        }

        int layoutId = ResourceTable.Layout_item_view_grid;

        MyAdapter mAdapter = new MyAdapter(this, mList, layoutId);
        mAdapter.setNumColumns(3);
        mAdapter.addHeaderView(headerView);
        mAdapter.addFooterView(footerView);
        recyclerView.setItemProvider(mAdapter);
    }

    @Override
    public void onClick(Component component) {
        Intent intent = new Intent();
        Operation operation;
        switch (component.getId()) {
            case ResourceTable.Id_menu1:
                operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.headerfooter.songhang.smartheaderfooterrecyclerview")
                        .withAbilityName("com.headerfooter.songhang.smartheaderfooterrecyclerview.MainAbility")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
                terminateAbility();
                break;
            case ResourceTable.Id_menu2:
                operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.headerfooter.songhang.smartheaderfooterrecyclerview")
                        .withAbilityName("com.headerfooter.songhang.smartheaderfooterrecyclerview.GridAbility")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
                terminateAbility();
                break;
            case ResourceTable.Id_menu3:
                operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName("com.headerfooter.songhang.smartheaderfooterrecyclerview")
                        .withAbilityName("com.headerfooter.songhang.smartheaderfooterrecyclerview.StaggeredAbility")
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
                terminateAbility();
                break;
            default:
                break;
        }
        menuDialog.destroy();
    }

    @Override
    protected void onBackPressed() {
        terminateAbility();
    }

    private static class MyAdapter extends GridViewAdapter<String> {
        public MyAdapter(Context context, List<String> data, int layoutId) {
            super(context, data, layoutId);
        }

        @Override
        public void convert(GridViewHolder holder, int[] positions, List<String> models) {
            Text textView = holder.getTextView(ResourceTable.Id_tv_txt1);
            Text textView2 = holder.getTextView(ResourceTable.Id_tv_txt2);
            Text textView3 = holder.getTextView(ResourceTable.Id_tv_txt3);
            textView.setVisibility(Component.INVISIBLE);
            textView2.setVisibility(Component.INVISIBLE);
            textView3.setVisibility(Component.INVISIBLE);
            for (int i = 0; i < positions.length; i++) {
                switch (i) {
                    case 0:
                        textView.setText(models.get(i));
                        textView.setVisibility(Component.VISIBLE);
                        break;
                    case 1:
                        textView2.setText(models.get(i));
                        textView2.setVisibility(Component.VISIBLE);
                        break;
                    case 2:
                        textView3.setText(models.get(i));
                        textView3.setVisibility(Component.VISIBLE);
                        break;
                    default:
                        break;
                }
            }
        }

        @Override
        public void setNumColumns(int numColumns) {
            super.setNumColumns(numColumns);
        }

        @Override
        public void addHeaderView(Component header) {
            super.addHeaderView(header);
        }

        @Override
        public void addFooterView(Component footer) {
            super.addFooterView(footer);
        }

        @Override
        public void setEmptyView(Component component) {
            super.setEmptyView(component);
        }

        @Override
        public void refresh(boolean isAdd) {
            super.refresh(isAdd);
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        if(menuDialog != null && menuDialog.isShowing()){
            outState.putBooleanValue("isShowMenu", true);
        }
    }

    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        boolean isShowMenu = inState.getBooleanValue("isShowMenu");
        if(isShowMenu){
            new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                @Override
                public void run() {
                    int screenWidth = AttrHelper.vp2px(250, getContext());
                    int menuHeight = AttrHelper.vp2px(150, getContext());
                    menuDialog = new MenuDialog(getContext(), menu, screenWidth, menuHeight, ResourceTable.Layout_menu_tab);
                    menuDialog.initListener(GridAbility.this);
                    menuDialog.show();
                }
            });
        }
    }
}
